package day01;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/21 15:00
 * 上浮--下潜--堆化   重点掌握!!!
 */
public class MaxHeap {
    int[] array;
    int size;

    public MaxHeap(int capacity) {
        array = new int[capacity];
    }

    public MaxHeap(int[] array) {
        this.array = array;
        this.size = array.length;
        // 建队
        heapify();
    }

    // 建堆
    public void heapify() {
        // 1.找到最后一个非叶子节点 (size / 2) - 1
        for (int i = (size / 2) - 1; i >= 0; i--) {
            // 2.下潜
            down(i);
        }
    }

    // 查看堆顶元素
    public int peek() {
        if (array.length < 1) {
            return -1;
        }
        return array[0];
    }

    // 删除堆顶元素
    public int poll() {
        int top = array[0];
        // 和最后一个叶子交换
        swap(0, size - 1);
        size--;
        // 调整堆 下潜
        down(0);
        return top;
    }

    // 替换
    public void replace(int replaced) {
        array[0] = replaced;
        down(0);
    }

    public boolean offer(int offered) {
        if (size == array.length) {
            return false;
        }
        up(offered);
        size++;
        return true;
    }

    public void up(int offered) {
        int child = size;
        while(size > 0) {
            int parent = (child - 1) / 2;
            if (offered > array[parent]) {
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }

    // 删除指定元素
    public int poll(int index) {
        int deleted = array[index];
        swap(index, size - 1);
        size--;
        down(index);
        return deleted;
    }

    public void down(int parent) {
        int left = parent * 2 + 1;
        int right = left + 1;
        int max = parent;
        // 首先不能越界
        if (left < size && array[left] > array[max]) {
            max = left;
        }
        if (right < size && array[right] > array[max]) {
            max = right;
        }
        if (max != parent) {
            // 交换
            swap(max, parent);
            // 继续下潜
            down(max);
        }
    }

    public void swap(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
